<?php

namespace G\User;

use App\Third\Wechat\EasyWechat;
use Core\Http\Request;
use Core\Log\Logger;
use Core\Support\Json;
use Core\Support\Redis;
use Core\Support\SingleTon;
use G\User\Model\LoginModel;
use G\User\Model\UserModel;

class AuthService
{
    use SingleTon;

    // 登录用户信息
    protected $user;
    // Token
    protected $token;
    // 过期时间
    protected $expire;
    // 是否可以多人登录
    protected $multiple;
    // 设备标示
    protected $device;

    /**
     * 使用账号登录
     */
    public function login($account, $password)
    {
        $user = UserModel::where('code', $account)->first();

        // 验证信息
        if ($user && $user->authentication($password)) {
            $this->saveLogin($user);
        }
    }

    /**
     * 微信登录
     */
    public function loginWeChat($code)
    {
        // 获取微信用户信息
        $wxUserInfo = EasyWechat::code2session($code);
        if ($wxUserInfo && $wxUserInfo->errcode != 0) {
            Logger::error("[用户登录] 获取微信用户信息失败", ['code' => $code, 'response' => $wxUserInfo]);
        }

        // 使用微信信息登录
        if ($wxUserInfo && isset($wxUserInfo->openid)) {
            // 获取用户信息 & 如果不存在创建一个新用户
            $user = $this->getUserByOpenIdOrNew($wxUserInfo->openid);

            if ($user) {
                $this->saveLogin($user);
            }
        }
    }

    /**
     * 获取当前登录用户信息
     */
    public function user()
    {
        return $this->user;
    }

    public function setUser(?UserModel $user)
    {
        $this->user = $user;
        return $this;
    }

    /**
     * 获取认证Token
     */
    public function token()
    {
        return $this->token;
    }

    /**
     * 设置Token
     */
    public function setToken($token)
    {
        $this->token = $token;
        return $this;
    }

    /**
     * 获取有效期
     */
    public function expire()
    {
        return $this->expire;
    }

    /**
     * 获取当前登录用户UID
     */
    public function uid()
    {
        if ($this->user) {
            return $this->user->id;
        }

        return null;
    }

    /**
     * 是否登录
     */
    public function check()
    {
        return $this->user ? true : false;
    }

    /**
     * 保存登录信息
     */
    protected function saveLogin(UserModel $user)
    {
        $now          = time();
        $this->token  = md5(crypt(sprintf("%8d-%s", $user->id, random_bytes(20)), APP_SLAT));
        $this->expire = $now + env('SESSION_LIFETIME', 7 * 24) * 60;
        $this->user   = $user;
        $this->device = $this->device ?: LoginModel::DEVICE_WEB;

        $loginAttributes = [
            'uid'       => $user->id,
            'token'     => $this->token,
            'device'    => $this->device,
            'expire'    => $this->expire,
            'ipaddr'    => Request::getInstance()->getClientIp(),
            'last'      => $now,
            'ua'        => Request::getInstance()->header('User-Agent'),
        ];

        // 不允许重复登录
        // if ($this->multiple !== true) {
        //     $login = LoginModel::whereUid($user->id)->whereDevice($this->device)->first();
        //     if ($login) {
        //         $login->delete();
        //         // Delete Cache
        //         Redis::store(DXE_SESSION)->del($login->token);
        //     }
        // }

        // LoginModel::create($loginAttributes)->save();
        Redis::store(DXE_SESSION)->setex($this->token, $this->expire - $now, Json::encode($loginAttributes));
    }

    /**
     * 微信登录, 如果用户不存在创建新的
     */
    protected function getUserByOpenIdOrNew($openId)
    {
        $user = UserModel::where('wx_openid', $openId)->first();
        if (empty($user)) {
            $user = UserModel::create([
                'wx_openid' => $openId,
            ]);
        }

        return $user;
    }
}
